package com.library.ui;

import com.library.service.LoginService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ChangePasswordDialog extends JDialog {
    private JTextField managerIdField;
    private JPasswordField oldPasswordField;
    private JPasswordField newPasswordField;
    private JPasswordField confirmPasswordField;
    private LoginService loginService = new LoginService();

    public ChangePasswordDialog(JFrame parent) {
        super(parent, "修改密码", true);
        setLayout(new GridLayout(4, 2));

        JLabel managerIdLabel = new JLabel("管理员编号：");
        managerIdField = new JTextField();
        JLabel oldPasswordLabel = new JLabel("旧密码：");
        oldPasswordField = new JPasswordField();
        JLabel newPasswordLabel = new JLabel("新密码：");
        newPasswordField = new JPasswordField();
        JLabel confirmPasswordLabel = new JLabel("确认新密码：");
        confirmPasswordField = new JPasswordField();

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String managerId = managerIdField.getText();
                String oldPassword = new String(oldPasswordField.getPassword());
                String newPassword = new String(newPasswordField.getPassword());
                String confirmPassword = new String(confirmPasswordField.getPassword());

                if (!newPassword.equals(confirmPassword)) {
                    JOptionPane.showMessageDialog(null, "新密码和确认密码不一致");
                    return;
                }

                if (loginService.changePassword(managerId, oldPassword, newPassword)) {
                    JOptionPane.showMessageDialog(null, "密码修改成功");
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(null, "密码修改失败，请检查管理员编号和旧密码");
                }
            }
        });

        add(managerIdLabel);
        add(managerIdField);
        add(oldPasswordLabel);
        add(oldPasswordField);
        add(newPasswordLabel);
        add(newPasswordField);
        add(confirmPasswordLabel);
        add(confirmPasswordField);
        add(new JLabel());
        add(saveBtn);

        setSize(300, 200);
        setLocationRelativeTo(parent);
        setVisible(true);
    }
}